<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="充电站名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入充电站名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:chargeStation:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:chargeStation:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:chargeStation:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:chargeStation:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="toFl"
          v-hasPermi="['business:chargeStation:export']"
          >费率记录</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="chargeStationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="充电站信息表" align="center" prop="stationId" /> -->
      <el-table-column label="充电站名称" align="center" prop="stationName" :show-overflow-tooltip="true"/>
      <el-table-column
        label="充电站地理位置"
        align="center"
        prop="stationAddr"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="充电站状态" align="center" prop="stationStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_station_status"
            :value="scope.row.stationStatus"
            :show-overflow-tooltip="true"
          />
          <!-- <el-switch v-model="scope.row.stationStatus" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch> -->
        </template>
      </el-table-column>
      <!-- <el-table-column label="充电桩数量" align="center" prop="stakeNumber" /> -->
      <el-table-column label="运营管理" align="center" prop="operaMana" />
      <el-table-column
        label="总额定功率"
        align="center"
        prop="totalRatedPower"
      />
      <el-table-column label="是否展示" align="center" prop="wxMiniappShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.wxMiniappShow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="getchangeShow(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="电站类型" align="center" prop="stationType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_station_type"
            :value="scope.row.stationType"
          />
        </template>
      </el-table-column>
      <el-table-column label="电站属性" align="center" prop="stationAttribute">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_station_attribute"
            :value="scope.row.stationAttribute"
          />
        </template>
      </el-table-column>

      <el-table-column label="停车费用" align="center" prop="parkingFees" />
      <el-table-column
        label="电站标签"
        align="center"
        prop="stationTag"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_station_tag"
            :value="scope.row.stationTag"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-office-building"
            @click="handleStake(scope.row)"
            v-hasPermi="['business:chargeStation:edit']"
            >充电桩</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:chargeStation:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:chargeStation:remove']"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充电站信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="充电站名称" prop="stationName">
              <el-input
                v-model="form.stationName"
                placeholder="请输入充电站名称"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="充电站ID" prop="stationID">
              <el-input
                v-model="form.stationID"
                placeholder="请输入充电站ID"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运营商ID" prop="operaorID">
              <el-input
                v-model="form.operaorID"
                placeholder="请输入运营商ID"
                maxlength="9"
                show-word-limit
              />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="8">
            <el-form-item label="设备所属ID" prop="equipmentOwnerID">
              <el-input
                v-model="form.equipmentOwnerID"
                placeholder="请输入设备所属ID"
                maxlength="9"
                show-word-limit
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="国家代码" prop="countryCode">
              <el-input
                v-model="form.countryCode"
                placeholder="请输入国家代码"
                maxlength="2"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址" prop="stationAddr">
              <el-input
                v-model="form.stationAddr"
                placeholder="请输入详细地址"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务电话" prop="serviceTel">
              <el-input
                v-model="form.serviceTel"
                placeholder="请输入服务电话"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车位数量" prop="parkNums">
              <el-input v-model="form.parkNums" placeholder="请输入车位数量" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="充电站类型" prop="stationType">
              <el-select
                v-model="form.stationType"
                placeholder="请选择充电站类型"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="dict in dict.type.charge_station_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="充电站属性" prop="stationAttribute">
              <el-select
                v-model="form.stationAttribute"
                placeholder="请选择充电站属性"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="dict in dict.type.charge_station_attribute"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="充电站公告" prop="stationNotice">
              <el-input
                v-model="form.stationNotice"
                placeholder="请输入充电站公告"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="充电桩数量" prop="stakeNumber">
              <el-input-number v-model="form.stakeNumber" placeholder="请输入充电站下充电桩数量" style="width: 100%;" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="电站状态" prop="stationStatus">
              <el-select
                v-model="form.stationStatus"
                placeholder="请选择电站状态"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="dict in dict.type.charge_station_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在省市区" prop="stationProvince">
              <el-cascader
                v-model="form.stationProvince"
                :options="regionData"
                :props="{ 
                  expandTrigger: 'hover',
                }"
                placeholder="请选择省市区"
                @change="handleRegionChange"
                style="width: 100%"
              />
            </el-form-item>

            <!-- :props="{ 
                  expandTrigger: 'hover',
                  label: 'label', // 显示的文本字段
                  value: 'label'  // 选中后存储的是label（中文）而非value（编码）
                }" -->
          </el-col>
          <el-col :span="8">
            <el-form-item label="停车费用" prop="parkingFees">
              <el-input
                v-model="form.parkingFees"
                placeholder="请输入停车费用"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="站点等级" prop="stationLevel">
              <el-select v-model="form.stationLevel" placeholder="请选择站点等级" style="width: 100%;" filterable clearable>
                <el-option v-for="dict in dict.type.charge_station_level" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="运营管理" prop="operaMana">
              <el-input
                v-model="form.operaMana"
                placeholder="请输入运营管理"
                maxlength="40"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总额定功率" prop="totalRatedPower">
              <el-input
                v-model="form.totalRatedPower"
                placeholder="请输入总额定功率（kw）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否展示" prop="wxMiniappShow">
              <el-radio-group v-model="form.wxMiniappShow">
                <el-radio :label="true" :value="true">是</el-radio>
                <el-radio :label="false" :value="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="停车费用" prop="parkingFees">
              <el-input v-model="form.parkingFees" placeholder="请输入停车费用" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="经度" prop="latitude">
              <el-input-number
                v-model="form.latitude"
                placeholder="请输入经度"
                :precision="6"
                :min="-180"
                :max="180"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纬度" prop="longitude">
              <el-input-number
                v-model="form.longitude"
                placeholder="请输入纬度"
                :precision="6"
                :min="-90"
                :max="90"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电站标签" prop="stationTag">
              <el-select
                v-model="form.stationTag"
                placeholder="请选择电站标签"
                style="width: 100%"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="dict in dict.type.charge_station_tag"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="站点图片" prop="stationImg">
          <el-input v-model="form.stationImg" placeholder="请输入站点图片" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--充电桩 -->
    <el-dialog
      :title="title"
      :visible.sync="openStake"
      width="60%"
      append-to-body
    >
      <Stake :stationId="stationId" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="openStake = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listchargeStation,
  getchargeStation,
  delchargeStation,
  addchargeStation,
  updatechargeStation,
  changeShow,
} from "@/api/business/chargeStation";

import { listStake } from "@/api/business/stake";
import Stake from "./stake.vue";

import { regionData, CodeToText } from "element-china-area-data";
export default {
  name: "chargeStation",
  dicts: [
    "charge_station_status",
    "charge_station_level",
    "charge_station_position",
    "charge_station_type",
    "charge_station_attribute",
    "charge_station_tag",
  ],
  components: { Stake },
  data() {
    var validatePhone = (rule, value, callback) => {
      // 手机号正则：仅支持13/14/15/16/17/18/19开头的11位纯数字
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!value) {
        callback(new Error("请输入服务电话（手机号）"));
      } else if (!phoneReg.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };

    // 经度验证：仅校验空值和范围
    var validateLat = (rule, value, callback) => {
      if (value === null || value === undefined || value == 0) {
        callback(new Error("请输入经度"));
      } else if (value < -180 || value > 180) {
        callback(new Error("经度范围应为 -180 ~ 180"));
      } else {
        callback();
      }
    };
    // 纬度验证：仅校验空值和范围
    var validateLon = (rule, value, callback) => {
      if (value === null || value === undefined || value == 0) {
        callback(new Error("请输入纬度"));
      } else if (value < -90 || value > 90) {
        callback(new Error("纬度范围应为 -90 ~ 90"));
      } else {
        callback();
      }
    };
    return {
      regionData: regionData,
      stationId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充电站信息表格数据
      chargeStationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示充电桩弹出层
      openStake: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        stationAddr: null,
        stationStatus: null,
        stakeNumber: null,
        operaMana: null,
        parkingFees: null,
        stationTag: null,
        stationPosition: null,
        stationLevel: null,
        serviceHotline: null,
        stationImg: null,
        params: {
          centerLat: "000",
        },
        numSSQ: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stationName: [
          { required: true, message: "充电站名称不能为空", trigger: "blur" },
        ],
        stationProvince: [
          { required: true, message: "请选择省市区", trigger: "change" },
        ],
        stationAddr: [
          { required: true, message: "地理位置不能为空", trigger: "blur" },
        ],
        latitude: [
          {
            validator: validateLat,
            required: true,
            trigger: "blur",
          }, // 新增范围校验
        ],
        longitude: [
          {
            validator: validateLon,
            required: true,
            trigger: "blur",
          }, // 新增范围校验
        ],
        stationStatus: [
          {
            required: true,
            message: "充电站状态不能为空",
            trigger: "change",
          },
        ],

        stationID: [
          {
            required: true,
            message: "充电站ID不能为空",
            trigger: "blue",
          },
        ],
        operaorID: [
          {
            required: true,
            message: "运营商ID不能为空",
            trigger: "blue",
          },
        ],
        equipmentOwnerID: [
          {
            required: true,
            message: "设备所属ID不能为空",
            trigger: "blue",
          },
        ],
        countryCode: [
          {
            required: true,
            message: "国家代码不能为空",
            trigger: "blue",
          },
        ],
        stationAddr: [
          {
            required: true,
            message: "详细地址不能为空",
            trigger: "blue",
          },
        ],
        serviceTel: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        parkNums: [
          {
            required: true,
            message: "车位数量不能为空",
            trigger: "blue",
          },
        ],
        stationType: [
          {
            required: true,
            message: "充电站类型不能为空",
            trigger: "change",
          },
        ],
        stationAttribute: [
          {
            required: true,
            message: "充电站属性不能为空",
            trigger: "change",
          },
        ],

        stationNotice: [
          {
            required: true,
            message: "充电站公告",
            trigger: "blur",
          },
        ],
        stakeNumber: [
          { required: true, message: "充电桩数量不能为空", trigger: "blur" },
          {
            type: "number",
            min: 1,
            message: "充电桩数量至少为1",
            trigger: "change",
          },
        ],
        operaMana: [
          { required: true, message: "运营管理不能为空", trigger: "blur" },
        ],
        totalRatedPower: [
          { required: true, message: "总额定功率不能为空", trigger: "blur" },
        ],
        wxMiniappShow: [
          { required: true, message: "是否展示", trigger: "blur" },
        ],

        parkingFees: [
          { required: true, message: "停车费用不能为空", trigger: "blur" },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "金额格式有误（最多2位小数）",
            trigger: "change",
          },
        ],
        stationTag: [
          { required: true, message: "电站标签不能为空", trigger: "change" },
        ],
        stationPosition: [
          { required: true, message: "电站位置不能为空", trigger: "blur" },
        ],
        stationLevel: [
          { required: true, message: "站点等级不能为空", trigger: "blur" },
        ],
        stationImg: [
          { required: true, message: "站点图片不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 是否展示切换
    getchangeShow(val) {
      console.log(val, "val");
      changeShow({
        stationIds: val.stationId,
        wxMiniappShow: val.wxMiniappShow,
      }).then((response) => {
        if (response.code == 200) {
          this.$message({ message: "切换成功", type: "success" });
          this.getList();
        } else {
          this.$message({ message: response.msg, type: "error" });
        }

        console.log(response, "response");
      });
    },
    handleRegionChange(value) {
      // console.log("选中的中文省市区：", value); // 输出 ['北京市', '市辖区', '东城区']
      this.form.stationProvince = value[value.length-1]; // 直接绑定中文数组
      console.log(this.form.stationProvince, 'this.form.stationProvince')
    },
    toFl() {
      console.log("123");
      this.$router.push("/business/chargeStation/chargeRate/index");
    },
    /** 查询充电站信息列表 */
    getList() {
      this.loading = true;
      listchargeStation(this.queryParams).then((response) => {
        this.chargeStationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stationName: null,
        stationAddr: null,
        stationStatus: null,
        stakeNumber: null,
        operaMana: null,
        parkingFees: null,
        stationProvince: null, // 省市区选择器初始为空数组
        stationTag: [], // 电站标签（多选）初始为空数组
        stationPosition: null,
        stationLevel: null,
        serviceHotline: null,
        stationImg: null,
        updateTime: null,
        createTime: null,
        latitude: null, // 经度
        longitude: null, // 纬度
        rateId: "123", // 保留原有默认值
        totalRatedPower: null,
        wxMiniappShow: true, // 是否展示默认选中"是"
        stationID: null, // 充电站ID
        operaorID: null, // 运营商ID
        equipmentOwnerID: null, // 设备所属ID
        countryCode: null, // 国家代码
        serviceTel: null, // 服务电话（手机号）
        parkNums: null, // 车位数量
        stationType: null, // 充电站类型
        stationAttribute: null, // 充电站属性
        stationNotice: null, // 充电站公告
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.stationId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.form.stationProvince = this.numSSQ;
      this.open = true;
      this.title = "添加充电站信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const stationId = row.stationId || this.ids;
      getchargeStation(stationId).then((response) => {
        this.form = response.data;
        console.log(response, "response");
        this.form.stationTag = this.form.stationTag?.split(",") || [];
        this.form.stationStatus = this.form.stationStatus + "";
        this.form.stationLevel = this.form.stationLevel + "";
        this.form.stationPosition = this.form.stationPosition + "";
        this.open = true;
        this.title = "修改充电站信息";
      });
    },
    handleStake(row) {
      // const stationIds = row.stationId || this.ids;
      this.stationId = row.stationId || this.ids;
      this.openStake = true;
      // this.$router.push({ path: '/business/chargeStation/stake/index', query: { stationId: stationIds } })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.stationProvince = Number(this.form.stationProvince);
          this.form.stationTag = this.form.stationTag.join(",");
          if (this.form.stationId != null) {
            updatechargeStation(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addchargeStation(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const stationIds = row.stationId || this.ids;
      this.$modal
        .confirm('是否确认删除充电站信息编号为"' + stationIds + '"的数据项？')
        .then(function () {
          return delchargeStation(stationIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/chargeStation/export",
        {
          ...this.queryParams,
        },
        `chargeStation_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
